<template>
  <resize-drawer
    :title="type === 'add' ? '新建语音' : '编辑语音'"
    :drawer="show"
    :size="576"
    :isShowMoreBtn="true"
    @onSave="saveVoiceFun"
    @onCloseDraw="closeDraw"
    @onCancelFun="closeDraw"
  >
    <template #column>
      <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
        <el-form-item label="语音名称" prop="name">
          <el-input type="text" v-model.trim="form.name" placeholder="请输入" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input
            type="textarea"
            v-model.trim="form.description"
            placeholder="请输入"
            autosize
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="voiceType">
          <el-radio-group v-model="form.voiceType" :disabled="type === 'edit'">
            <el-radio label="general_voice">普通语音<span class="tip">(可用于IVR语音流程的各节点中)</span></el-radio>
            <el-radio label="moh">等待语音<span class="tip">(仅用于服务组排队等待时客户侧的等待语音)</span></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="fileUrl" label="语音文件">
          <alert-msg
            content="请保证上传的语音遵守中华人民共和国有关法律规定，并符合《互联网新闻信息服务管理规则》。如有违反，需承担一切直接或间接引起的法律责任。"
            backgroundColor="rgba(243, 198, 61, 0.1)"
          >
            <template #icon>
              <i class="MC_iconfont MC_icon-jinggao-mian"></i>
            </template>
          </alert-msg>
          <upload-voice
            type="common"
            scope="ivr-music"
            class="upload-box"
            drag
            action=""
            accept=".wav"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :before-remove="cancleUpload"
          >
            <template #trigger>
              <!-- <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
                <div class="file-limit">
                  支持格式 wav 大小不超过3M<br />
                  如果非wav格式，将为您自动转码，转码后音质可能有损失
                </div>
              </div> -->
              <el-button>选择文件</el-button>
              <div class="file-limit">
                点击或将文件拖拽到此处上传<br />
                支持扩展名：.wav .mp3 大小不超过3M<br />
                如果非wav格式，将为您自动转码，转码后音质可能有损失！
              </div>
            </template>
          </upload-voice>
        </el-form-item>
      </el-form>
    </template>
  </resize-drawer>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, getCurrentInstance } from 'vue'
import resizeDrawer from '@/common/components/resize-drawer/index.vue'
import { addVoice, updateVoice } from '@app/call-center/apis/voice-library'
import { ElMessage } from 'element-plus'
import alertMsg from '@common/components/alert/index.vue'
import uploadVoice from '@common/components/upload/index.vue'
import mcCache from '@/common/utils/mc-get-cache'
interface State {
  title: string
  show: boolean
  fileList: Record<string, unknown>[]
  form: any
  rules: Record<string, unknown>
  type: string
  uploadCancel: boolean
}
const defaultForm = {
  name: '',
  voiceType: 'general_voice',
  description: '',
  fileUrl: '',
  fileName: '',
  fileType: ''
}
export default defineComponent({
  name: 'AddOrEditVoice',
  components: { resizeDrawer, alertMsg, uploadVoice },
  emits: ['onUpdateList'],
  setup(_, { emit }) {
    const state: State = reactive({
      title: '',
      show: false,
      fileList: [],
      form: defaultForm,
      rules: {
        name: [{ required: true, message: '请输入语音名称', trigger: 'blur' }],
        fileUrl: [{ required: true, message: '请上传语音文件', trigger: 'change' }]
      },
      type: 'add',
      uploadCancel: false
    })

    const instance: any = getCurrentInstance()

    const saveVoiceFun = () => {
      instance?.refs.formRef.validate((valid: boolean) => {
        if (valid) {
          const { name, fileUrl, fileType, fileName, description, voiceType, id } = state.form
          const sendData = {
            name,
            fileUrl,
            fileType,
            fileName,
            description,
            voiceType
          }
          ;(state.type === 'add' ? addVoice(sendData) : updateVoice({ ...sendData, id })).then((res) => {
            if (res.success) {
              ElMessage.success('保存成功')
              closeDraw()
              emit('onUpdateList')
              // 更新pinia
              if (state.type === 'add') {
                mcCache.$addOneCache('voiceLibrary', res.data, 'hasObj', 'id') // 新建
              } else {
                mcCache.$updateCache('voiceLibrary', res.data, 'id', 'hasObj') // 编辑
              }
            }
          })
        }
      })
    }

    const beforeUpload = (file: any) => {
      state.uploadCancel = false
      // 上传前验证文件合法性
      state.form.fileName = file.name.replace(/\s/g, '')
      const fileName = /[^.]+$/.exec(state.form.fileName)
      if (file.size / 1024 / 1024 > 3) {
        ElMessage({ message: '录音文件不能超过3M', type: 'error' })
        return false
      }
      if (fileName && fileName[0] !== 'wav') {
        ElMessage({ message: '仅支持上传.wav文件', type: 'error' })
        return false
      }
      state.form.fileType = fileName ? fileName[0] : 'wav'
    }

    const uploadError = () => {
      // 上传失败
      ElMessage({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
    }

    const uploadSuccess = (data: any) => {
      // 上传成功
      if (!state.uploadCancel) {
        state.form.fileUrl = data.url
        state.fileList = [{ name: data.name, url: data.url }]
      }
    }

    const cancleUpload = () => {
      // 取消上传
      state.uploadCancel = true
      state.form.fileUrl = ''
      state.fileList = []
    }

    const openUploadVoice = (type: string, row: any) => {
      // 打开抽屉
      state.type = type
      state.show = true
      state.form = { ...defaultForm, ...row }
      if (type === 'edit') {
        state.fileList = [{ name: row.fileName, url: row.fileUrl }]
      } else {
        state.fileList = []
      }
    }

    const closeDraw = () => {
      // 关闭抽屉
      state.show = false
    }

    return {
      ...toRefs(state),
      closeDraw,
      openUploadVoice,
      saveVoiceFun,
      beforeUpload,
      uploadError,
      uploadSuccess,
      cancleUpload,
      instance
    }
  }
})
</script>

<style lang="stylus" scoped>
.tip {
  margin-left: 10px;
  color: rgba(0, 0, 0, 0.36);
}

.MC_icon-jinggao-mian {
  color: var(--mc-warning-color);
  margin-right: 8px;
}

.upload-box {
  width: 100%;
  text-align: center;

  :deep(.el-upload-dragger) {
    height: 124px;
    border: 1px dashed var(--mc-gray4-color);
    background: var(--mc-gray2-color);
    padding: 16px 0;
  }

  .file-limit {
    font-size: 12px;
    line-height: 18px;
    color: rgba(0, 0, 0, 0.38);
    padding: 0;
    margin-top 8px
  }
}
</style>
